package com.example.demojenkins.login;

import com.alibaba.fastjson2.JSON;
import com.example.demojenkins.domain.AjaxResult;
import com.example.demojenkins.domain.ChildrenMenu;
import com.example.demojenkins.domain.LoginUser;
import com.example.demojenkins.domain.MenuList;
import com.example.demojenkins.entity.User;
import com.example.demojenkins.service.RoleService;
import com.example.demojenkins.service.UserRoleService;
import com.example.demojenkins.service.UserService;
import com.example.demojenkins.utils.JwtUtils;
import com.example.demojenkins.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

/**
 * @version 1.0
 * @author: LZ
 * @description: 登陆
 * @since 2024-08-19 18:03
 */
@RestController
@RequestMapping("/api")
public class Login {

    @Autowired
    RedisCache redisCache;
    @Resource
    private RoleService roleService;

    @Resource
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;

    @Autowired
    private AuthenticationManager authenticationManager;



    @RequestMapping("/dashboardLogin")
    public AjaxResult login(@RequestBody User userLogin) {
        AjaxResult ajax = AjaxResult.success("登陆成功");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userLogin.getUserName(),userLogin.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登陆失败!");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getUserId().toString();
        String jwt = JwtUtils.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token响应给前端
        HashMap<String,String> map = new HashMap<>();
        map.put("token",jwt);
        return new AjaxResult(200,"登陆成功",map);

//        if(Objects.isNull(authenticate)){
//            throw new RuntimeException("用户名或密码错误");
//        }
//        if (!redisCache.hasKey("loginCount")) {
//            redisCache.setCacheObject("loginCount", 0);
//        }
//        if (redisCache.hasKey("managerUser".concat(userLogin.getUserName()).concat(userLogin.getPassword()))) {
//            if ((int) redisCache.getCacheObject("loginCount") > 3) {
//                redisCache.expire("loginCount", 60L);
//                return AjaxResult.error(202, "登陆过于频繁!");
//            }
//            redisCache.setCacheObject("loginCount", (int) redisCache.getCacheObject("loginCount") + 1);
//            String jwt = JwtUtils.createJWT(JSON.toJSONString(userLogin));
//            System.out.println(jwt);
////            String token = JSON.toJSONString(userLogin);
//            ajax.put("token", jwt);
//            redisCache.setCacheObject("login:"+userLogin.getUserName(),userLogin);
//
//            return ajax;
//        }
//        return AjaxResult.error(202, "非内定用户!");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @RequestMapping("getInfo")
    public AjaxResult getInfo(String userName) {

        MenuList menuList = new MenuList();
        menuList.setName("产品管理");
        ChildrenMenu childrenMenu1 = new ChildrenMenu();
        childrenMenu1.setName("产品列表");
        ChildrenMenu childrenMenu2 = new ChildrenMenu();
        childrenMenu2.setName("产品分类");
        ArrayList<ChildrenMenu> objects = new ArrayList<>();
        objects.add(childrenMenu1);
        objects.add(childrenMenu2);
        menuList.setChildren(objects);

        MenuList menuList1 = new MenuList();
        menuList1.setName("商品管理");
        ChildrenMenu childrenMenu3 = new ChildrenMenu();
        childrenMenu3.setName("商品列表");
        ChildrenMenu childrenMenu4 = new ChildrenMenu();
        childrenMenu4.setName("商品汇总");
        ArrayList<ChildrenMenu> objects1 = new ArrayList<>();
        objects1.add(childrenMenu3);
        objects1.add(childrenMenu4);
        menuList1.setChildren(objects1);

//        MenuList menuList2 = new MenuList();
//        menuList2.setName("广告管理");
//        ChildrenMenu childrenMenu5 = new ChildrenMenu();
//        childrenMenu5.setName("广告列表");
//
//        ArrayList<ChildrenMenu> objects2 = new ArrayList<>();
//        objects2.add(childrenMenu5);
//
//        menuList2.setChildren(objects2);
        ArrayList<MenuList> objects3 = new ArrayList<>();
        objects3.add(menuList);
        objects3.add(menuList1);
//        objects3.add(menuList2);


//        String jsonString = JSON.toJSONString(objects3);
//        System.out.println(objects3);
        AjaxResult ajax = new AjaxResult(200, "成功", objects3);
        System.out.println(ajax);
//        System.out.println(userName);
//        AjaxResult ajax = AjaxResult.success();
//        // 角色集合
//        User user = userService.queryByUserName("manager");
//        UserRole userRole = userRoleService.queryById(user.getUserId());
//        Role role = roleService.queryById(userRole.getRoleId());
//        Set<String> roles = new HashSet<>();
//        roles.add(role.getRoleName());
//        ajax.put("roles", JSON.toJSONString(roles));
//        System.out.println(ajax);
        return ajax;
    }
}
